package com.itcam.cm.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.itcam.cm.manager.mapper.CategoryMapper;
import com.itcam.cm.model.vo.product.CategoryExcelVo;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@NoArgsConstructor
public class CategoryReadListener extends AnalysisEventListener<CategoryExcelVo> {

    List<CategoryExcelVo> categoryExcelVos = new ArrayList<>();

    @Autowired
    CategoryMapper categoryMapper;

    public CategoryReadListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void invoke(CategoryExcelVo categoryExcelVo, AnalysisContext analysisContext) {
        categoryExcelVos.add(categoryExcelVo);
        if(categoryExcelVos.size()>=100){
            System.out.println("批处理：每100条数据插入一次数据库");
            System.out.println(categoryExcelVos.size());
            categoryMapper.batchInsert(categoryExcelVos);
            categoryExcelVos.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("CategoryReadListener收尾方法");
        categoryMapper.batchInsert(categoryExcelVos);
        categoryExcelVos.clear();
    }
}
